#include "modelitems.h"

ModelItems::ModelItems(QObject *parent) :
    QAbstractListModel(parent)
{
    qDebug()<<"items model init";
    itemsList = ListMaintence::getInstance()->collectionListContent();
    connect( ListMaintence::getInstance(),&ListMaintence::itemUpdate,
             [=]()
    {
        beginResetModel();
        endResetModel();
    });
}
QVariant ModelItems::data(const QModelIndex &index, int role) const
{    
    if (index.row() < 0 || index.row() >itemsList->length())
        return QVariant();
    if(role == ItemID)
        return itemsList->value(index.row());
    if(role == ItemName)
        return  getItemInfo(itemsList->value(index.row()),"name");
    if(role == ItemIcon)
    {
        return getItemInfo(itemsList->value(index.row()),"icon");
    }
}

int ModelItems::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return itemsList->length();
}

QString ModelItems::getItemInfo(QString _i, QString _p) const
{
    return  ListMaintence::getInstance()->itemInfo(_i,_p);
}


void ModelItems::addRow(const QString &_c)
{
    ListMaintence::getInstance()->addItem(_c);
    beginInsertRows(QModelIndex(),itemsList->indexOf(_c),itemsList->indexOf(_c));
    endInsertRows();
}

void ModelItems::remRow(const QString &_c)
{
    int _t = _c.toInt();
    ListMaintence::getInstance()->remItem(_c);
    beginRemoveRows(QModelIndex(), _t, _t);
    endRemoveRows();
}

QHash<int, QByteArray> ModelItems::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[ItemID] = "id";
    roles[ItemName] = "name";
    roles[ItemIcon] = "icon";
    return roles;
}
